import { z } from 'zod';
import { router, publicProcedure } from '../trpc';
import { protectedProcedure } from '../middleware';
import { AuthService } from '../../services/authService';
import { GoogleAuthService } from '../../services/googleAuthService';
import { createSuccessResponse, createErrorResponse } from '../../utils/response';

// 输入验证schemas
const loginSchema = z.object({
  email: z.string().email('Invalid email format'),
  password: z.string().min(6, 'Password must be at least 6 characters'),
});

const registerSchema = z.object({
  email: z.string().email('Invalid email format'),
  username: z.string().min(3, 'Username must be at least 3 characters'),
  password: z.string().min(6, 'Password must be at least 6 characters'),
});

const googleAuthSchema = z.object({
  googleToken: z.string().min(1, 'Google token is required'),
});

const changePasswordSchema = z.object({
  oldPassword: z.string().min(1, 'Old password is required'),
  newPassword: z.string().min(6, 'New password must be at least 6 characters'),
});

const resetPasswordSchema = z.object({
  email: z.string().email('Invalid email format'),
  newPassword: z.string().min(6, 'New password must be at least 6 characters'),
});

export const authRouter = router({
  /**
   * 用户登录
   */
  login: publicProcedure
    .input(loginSchema)
    .mutation(async ({ input }) => {
      try {
        const result = await AuthService.login(input);
        return createSuccessResponse(result, 'Login successful');
      } catch (error) {
        return createErrorResponse(
          error instanceof Error ? error.message : 'Login failed',
          'AUTH_ERROR'
        );
      }
    }),

  /**
   * 用户注册
   */
  register: publicProcedure
    .input(registerSchema)
    .mutation(async ({ input }) => {
      try {
        const result = await AuthService.register(input);
        return createSuccessResponse(result, 'Registration successful');
      } catch (error) {
        return createErrorResponse(
          error instanceof Error ? error.message : 'Registration failed',
          'AUTH_ERROR'
        );
      }
    }),

  /**
   * Google OAuth认证
   */
  googleAuth: publicProcedure
    .input(googleAuthSchema)
    .mutation(async ({ input }) => {
      try {
        if (!GoogleAuthService.isConfigured()) {
          return createErrorResponse(
            'Google OAuth not configured on server',
            'CONFIG_ERROR'
          );
        }

        // 验证Google token并获取用户信息
        const googleUserInfo = await GoogleAuthService.verifyGoogleToken(input.googleToken);

        // 使用Google用户信息进行认证
        const result = await AuthService.googleAuth(googleUserInfo);

        return createSuccessResponse(result, 'Google authentication successful');
      } catch (error) {
        return createErrorResponse(
          error instanceof Error ? error.message : 'Google authentication failed',
          'AUTH_ERROR'
        );
      }
    }),

  /**
   * 获取Google OAuth授权URL
   */
  getGoogleAuthUrl: publicProcedure
    .input(z.object({
      redirectUri: z.string().url('Invalid redirect URI')
    }))
    .query(async ({ input }) => {
      try {
        if (!GoogleAuthService.isConfigured()) {
          return createErrorResponse(
            'Google OAuth not configured on server',
            'CONFIG_ERROR'
          );
        }

        const authUrl = GoogleAuthService.generateAuthUrl(input.redirectUri);

        return createSuccessResponse({ authUrl }, 'Google auth URL generated');
      } catch (error) {
        return createErrorResponse(
          error instanceof Error ? error.message : 'Failed to generate auth URL',
          'AUTH_ERROR'
        );
      }
    }),

  /**
   * 使用Google授权码进行认证
   */
  googleAuthCallback: publicProcedure
    .input(z.object({
      code: z.string().min(1, 'Authorization code is required'),
      redirectUri: z.string().url('Invalid redirect URI')
    }))
    .mutation(async ({ input }) => {
      try {
        if (!GoogleAuthService.isConfigured()) {
          return createErrorResponse(
            'Google OAuth not configured on server',
            'CONFIG_ERROR'
          );
        }

        // 使用授权码获取访问令牌
        const tokens = await GoogleAuthService.getTokensFromCode(input.code, input.redirectUri);

        if (!tokens.access_token) {
          throw new Error('Failed to get access token from Google');
        }

        // 使用访问令牌获取用户信息
        const googleUserInfo = await GoogleAuthService.getUserInfoFromTokens(tokens.access_token);

        // 使用Google用户信息进行认证
        const result = await AuthService.googleAuth(googleUserInfo);

        return createSuccessResponse(result, 'Google authentication successful');
      } catch (error) {
        return createErrorResponse(
          error instanceof Error ? error.message : 'Google authentication failed',
          'AUTH_ERROR'
        );
      }
    }),

  /**
   * 获取当前用户信息
   */
  me: protectedProcedure
    .query(async ({ ctx }) => {
      try {
        return createSuccessResponse(
          { user: ctx.user },
          'User information retrieved'
        );
      } catch (_error) {
        return createErrorResponse(
          'Failed to get user information',
          'AUTH_ERROR'
        );
      }
    }),

  /**
   * 修改密码
   */
  changePassword: protectedProcedure
    .input(changePasswordSchema)
    .mutation(async ({ input, ctx }) => {
      try {
        await AuthService.changePassword(
          ctx.user.userId,
          input.oldPassword,
          input.newPassword
        );
        return createSuccessResponse(null, 'Password changed successfully');
      } catch (error) {
        return createErrorResponse(
          error instanceof Error ? error.message : 'Failed to change password',
          'AUTH_ERROR'
        );
      }
    }),

  /**
   * 重置密码 (管理员功能)
   */
  resetPassword: publicProcedure
    .input(resetPasswordSchema)
    .mutation(async ({ input }) => {
      try {
        await AuthService.resetPassword(input.email, input.newPassword);
        return createSuccessResponse(null, 'Password reset successfully');
      } catch (error) {
        return createErrorResponse(
          error instanceof Error ? error.message : 'Failed to reset password',
          'AUTH_ERROR'
        );
      }
    }),

  /**
   * 登出 (客户端处理，服务端只返回成功)
   */
  logout: protectedProcedure
    .mutation(async () => {
      // 在实际应用中，可能需要将token加入黑名单
      // 这里简单返回成功，客户端删除token
      return createSuccessResponse(null, 'Logout successful');
    }),
});
